package com.capture_pictures;

import org.springframework.http.HttpMethod;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName: CaptureOnePictures
 * @Author: ZhangYue26
 * @Description:抓取一个图片地址的图片
 * @Date: 2020-11-28
 */
public class CaptureOnePictures {

    public static void main(String[] args) {

        testGetphoto("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=168267180,2852841364&fm=26&gp=0.jpg",
                "D:\\temp",String.valueOf(System.nanoTime()),".jpg");

    }

    /**
      * <p>
      *     将图片下载至本地指定文件夹中
      * <p/>
      *
	  * @param requestUrl 图片完整URL
	  * @param rootPath 图片存放目录(字符串最后一位不包括 \ )
	  * @param fileName 图片名称（不包括后缀）
	  * @param suffix  图片后缀名(包括 . )
      * @return void
      * @author Jack.Zhang 2021/9/27 16:51
      * @since 1.0.0
      * @see
      */
    private static void testGetphoto(String requestUrl,String rootPath,String fileName,String suffix) {
        URL url = null;
        final String fileNamePath = rootPath + "\\" + fileName + suffix;
        try {
            final File file1 = new File(rootPath);
            if (file1.isDirectory() && !file1.exists()) {
                file1.mkdirs();
            }
            url = new URL(requestUrl);
            HttpURLConnection urlConnection =(HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod(HttpMethod.GET.toString());
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                InputStream inputStream = urlConnection.getInputStream();
                File file = new File(fileNamePath);
                OutputStream outputStream = new FileOutputStream(file);
                byte[] bytes = null;
                int read = 0;
                do {
                    bytes = new byte[1024 * 8];
                    read = inputStream.read(bytes);
                    outputStream.write(bytes);
                    outputStream.flush();
                } while (read != -1);
                outputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("图片下载完成--" + fileNamePath);
    }
}
